package com.anji.plus.gaea.controller.advice;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.anji.plus.gaea.annotation.DetailView;
import com.anji.plus.gaea.annotation.QueryView;
import com.anji.plus.gaea.annotation.resolver.mask.DataMaskEnabled;
import com.anji.plus.gaea.annotation.resolver.mask.MaskResolveUtil;
import com.anji.plus.gaea.holder.UserContentHolder;

/**
 * 结合 @QueryView,@DetailView 处理脱敏信息
 * 替换掉 com.anji.plus.gaea.annotation.resolver.mask.GaeaMaskJsonSerialize
 * @author WongBin
 * @date 2022/9/1
 */
@Aspect
@Component
public class GaeaMaskResolver {

    @Autowired(required = false)
    private DataMaskEnabled maskEnabled;

    @Pointcut("@annotation(com.anji.plus.gaea.annotation.DetailView) ||@annotation(com.anji.plus.gaea.annotation.QueryView)")
    private void pointCut() {
    }

    @Around(value = "pointCut()")
    public Object aroundHandler(ProceedingJoinPoint pjp) throws Throwable {
        Signature sig = pjp.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = pjp.getTarget();
        Method currMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        DetailView detailTag = currMethod.getAnnotation(DetailView.class);
        QueryView queryTag = currMethod.getAnnotation(QueryView.class);

        Object ret = pjp.proceed(pjp.getArgs());

        if(maskEnabled != null && maskEnabled.enable(detailTag,queryTag,UserContentHolder.getContext())){
            MaskResolveUtil.resolve(ret,null);
        }
        return ret;
    }
}
